package com.life.wd.service.Imp;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.life.wd.dto.ProductAddRequest;
import com.life.wd.dto.ProductQueryRequest;
import com.life.wd.dto.ProductUpdateRequest;
import com.life.wd.entity.Product;
import com.life.wd.entity.Supplier;
import com.life.wd.exception.BusinessException;
import com.life.wd.mapper.ProductMapper;
import com.life.wd.mapper.SupplierMapper;
import com.life.wd.result.PageResult;
import com.life.wd.service.ProductService;
import com.life.wd.service.SupplierService;
import com.life.wd.vo.ProductVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
@Transactional(rollbackFor = Exception.class)
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private SupplierService supplierService;

    @Override
    public Long addProduct(ProductAddRequest request) throws IOException {
        // 校验供应商是否存在
        supplierService.validateSupplierExists(request.getSupplierId());

        // 构建产品实体
        Product product = new Product();
        product.setCategory(request.getCategory());
        product.setSupplierId(request.getSupplierId());

        // 处理上传的图片
        MultipartFile file = request.getPosterUrl();
        if (file != null && !file.isEmpty()) {
            product.setPosterUrl(file.getBytes());
            product.setPosterContentType(file.getContentType());
        }

        // 插入数据库
        productMapper.insert(product);

        return product.getId();
    }


    @Override
    public PageResult listProducts(ProductQueryRequest queryRequest) {
        PageHelper.startPage(queryRequest.getPage(), queryRequest.getPageSize());
        Page<Product> suppliers = productMapper.listProducts(queryRequest);
        return new PageResult(suppliers.getTotal(), suppliers.getResult());
    }

    @Override
    public ProductVO getProductById(Long id) {
        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new BusinessException("401", "产品不存在");
        }
        return convertToVO(product);
    }

    @Autowired
    private SupplierMapper supplierMapper;


    private ProductVO convertToVO(Product product) {
        ProductVO vo = new ProductVO();
        BeanUtils.copyProperties(product, vo);

        // 查询供应商信息
        Supplier supplier = supplierMapper.getById(product.getSupplierId());
        if (supplier != null) {
            vo.setSupplierName(supplier.getCompanyName());
        }

        return vo;
    }

    @Override
    public boolean updateProduct(ProductUpdateRequest request) throws IOException {
        // 验证产品是否存在
        Product product = productMapper.getById(request.getId());
        if (product == null) {
            throw new IllegalArgumentException("产品不存在，ID: " + request.getId());
        }

        // 更新产品信息
        if (request.getCategory() != null) {
            product.setCategory(request.getCategory());
        }

        if (request.getSupplierId() != null) {
            product.setSupplierId(request.getSupplierId());
        }

        // 处理上传的图片（如果有）
        MultipartFile file = request.getPosterUrl();
        if (file != null && !file.isEmpty()) {
            product.setPosterUrl(file.getBytes());
            product.setPosterContentType(file.getContentType());
        }

        // 更新数据库
        int rows = productMapper.update(product);
        return rows > 0;
    }

    @Override
    public boolean deleteProduct(Long id) {
        // 验证产品是否存在
        if (productMapper.getById(id) == null) {
            throw new IllegalArgumentException("产品不存在，ID: " + id);
        }

        // 执行删除操作
        int rows = productMapper.delete(id);
        return rows > 0;
    }
}